package org.example.runningforum.mapper;

import org.apache.ibatis.annotations.*;
import org.example.runningforum.modle.Article;
import org.example.runningforum.modle.ArticleDetail;

import java.util.List;

@Mapper
public interface IArticleMapper {
    // 创建文章
    @Insert("INSERT INTO article (title, content, user_id) " +
            "VALUES (#{title}, #{content}, #{userId})")
    @Options(useGeneratedKeys = true, keyProperty = "articleId", keyColumn = "article_id")
    int insertArticle(Article article);

    // 获取文章详情
    @Select("SELECT * FROM article WHERE article_id = #{articleId} AND is_deleted = 0")
    Article selectArticleById( Long articleId);

    // 增加浏览次数
    @Update("UPDATE article SET view_count = view_count + 1 WHERE article_id = #{articleId}")
    int increaseViewCount( Long articleId);


    //查询文章详细信息
    @Select("SELECT " +
            "a.article_id, " +
            "a.title, " +
            "a.content, " +
            "a.view_count, " +
            "a.created_at, " +
            "u.username AS author, " +
            "u.level " +
            "FROM article a " +
            "JOIN user u ON a.user_id = u.user_id " +
            "WHERE a.article_id = #{articleId} AND a.is_deleted = 0")
    ArticleDetail selectArticleByArticleId(Long articleId);

    // 复杂查询：根据标题搜索文章
    @Select("SELECT a.*, u.username FROM article a " +
            "JOIN user u ON a.user_id = u.user_id " +
            "WHERE a.title LIKE CONCAT('%', #{keyword}, '%') " +
            "AND a.is_deleted = 0")
    List<Article> searchArticlesByTitle( String keyword);

/*
 * 查询所有文章列表（根据浏览量排序）
 * 返回类型为包含作者信息的ArticleDetail
* */
    @Select("SELECT " +
            "a.article_id, " +
            "a.title, " +
            "a.content, " +
            "a.view_count, " +
            "a.created_at, " +
            "u.username AS author " +
            "FROM article a " +
            "JOIN user u ON a.user_id = u.user_id " +
            "WHERE a.is_deleted = 0 " +
            "ORDER BY a.view_count DESC")
    List<ArticleDetail> selectArticlesByViews();

/*
* 查询所有文章列表（根据创建时间排序）
* 返回类型为包含作者信息的ArticleDetail
* */
    @Select("SELECT " +
            "a.article_id, " +
            "a.title, " +
            "a.content, " +
            "a.view_count, " +
            "a.created_at, " +
            "u.username AS author " +
            "FROM article a " +
            "JOIN user u ON a.user_id = u.user_id " +
            "WHERE a.is_deleted = 0 " +
            "ORDER BY a.created_at DESC")
    List<ArticleDetail> selectArticlesByCreateTime();


    @Select("SELECT COUNT(*) AS article_count \n" +
            "FROM article \n" +
            "WHERE is_deleted = 0;")
    Integer selectArticleCount();

}